package com.example.netty.lengthfield.server;

import cn.hutool.core.util.ByteUtil;
import com.example.netty.common.utils.ByteUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;

/**
 * <p></p>
 *
 * @author xin
 * @version 2023/11/2 16:39
 **/
public class LengthFieldServerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(LengthFieldServerHandler.class);


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.debug("收到客户端消息");
        try {
//            ByteBuf buf = (ByteBuf) msg;
//            byte[] bytes = new byte[buf.readableBytes()];
//            buf.readBytes(bytes);
            byte[] bytes = (byte[]) msg;
            String body = new String(new byte[]{bytes[0], bytes[1], bytes[2], bytes[3], bytes[4]});
            body = body + ByteUtil.bytesToInt(new byte[]{bytes[5], bytes[6], bytes[7], bytes[8]});
            byte[] bodyBytes = new byte[bytes.length - 9];
            System.arraycopy(bytes, 9, bodyBytes, 0, bodyBytes.length);
            body = body + new String(bodyBytes);
            System.out.println("-----client start------| \n " + body + " \n| ------client end------");
            // 长度 5

            // 服务端给客户端发送消息，以字符串 编码、解码方式
            String sendMsg = "我是服务端给客户端的消息;";
            ctx.channel().writeAndFlush(sendMsg);
        } catch (Exception e) {
            logger.error("接收数据异常", e);
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
